package com.example.bookkeep.Fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;
import com.example.bookkeep.Bill.AddBillActivity;
import com.example.bookkeep.R;
import com.example.bookkeep.Utils.URLUtils;
import com.example.bookkeep.model.BookKeep;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FinanceFragment extends Fragment {

    private LinearLayout containerBills;
    private static final int REQUEST_ADD_BILL = 1001;

    public FinanceFragment() {
        // Required empty public constructor
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_finance, container, false);

        containerBills = view.findViewById(R.id.containerBills);
        super.onViewCreated(view, savedInstanceState);

        LinearLayout btnAddBill = view.findViewById(R.id.btnAddBill);
        btnAddBill.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AddBillActivity.class);
            startActivityForResult(intent, REQUEST_ADD_BILL);
        });

        fetchBillData(inflater);  // 加载账单数据

        return view;
    }


private void addBillItem(LayoutInflater inflater, BookKeep bill) {
    View billView = inflater.inflate(R.layout.item_bill, containerBills, false);
    // 添加账单按钮

    //  设置账单信息

    TextView tvType = billView.findViewById(R.id.tvType);
    TextView tvAmount = billView.findViewById(R.id.tvAmount);
    TextView tvCategory = billView.findViewById(R.id.tvCategory);
    TextView tvTime = billView.findViewById(R.id.tvTime);
    TextView tvRemark = billView.findViewById(R.id.tvRemark);
    Button btnEdit = billView.findViewById(R.id.btnEdit);

    tvType.setText(bill.getType() == 1 ? "收入" : "支出");
    tvAmount.setText("￥" + bill.getPrice());
    tvCategory.setText(bill.getCategory());
    tvTime.setText(bill.getAddTime());
    tvRemark.setText(bill.getRemark());

    billView.setTag(bill.getBookKeepId());

    btnEdit.setOnClickListener(v -> showEditDialog(bill, inflater));

    containerBills.addView(billView);
}


    private void fetchBillData(LayoutInflater inflater) {
        OkHttpClient client = new OkHttpClient();

        SharedPreferences prefs = requireContext().getSharedPreferences("auth", Context.MODE_PRIVATE);
        String token = prefs.getString("token", "");

        if (token == null || token.isEmpty()) {
            Log.e("FinanceFragment", "Token 不存在");
            return;
        }

        String url = URLUtils.BASE_URL + "/bookKeeps";

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("FinanceFragment", "请求失败: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String jsonData = response.body().string();
                    String content = JSON.parseObject(jsonData).getString("content");
                    try {
                        List<BookKeep> bills = JSON.parseArray(content, BookKeep.class);

                        requireActivity().runOnUiThread(() -> {
                            Map<String, List<BookKeep>> groupedBills = new LinkedHashMap<>();

                            // 按月份（如“2025-06”）分组
                            for (BookKeep bill : bills) {
                                String month = bill.getAddTime().substring(0, 7); // 取前7位："2025-06"
                                groupedBills.computeIfAbsent(month, k -> new ArrayList<>()).add(bill);
                            }

                            for (Map.Entry<String, List<BookKeep>> entry : groupedBills.entrySet()) {
                                String month = entry.getKey();
                                List<BookKeep> monthlyBills = entry.getValue();

                                // 添加月份分割线
                                addMonthSeparator(inflater, month);

                                // 添加该月账单项
                                for (BookKeep bill : monthlyBills) {


                                    addBillItem(inflater,bill);
                                }
                            }
                        });

                    } catch (Exception e) {
                        Log.e("FinanceFragment", "Fastjson 解析出错: " + e.getMessage());
                    }
                } else {
                    Log.e("FinanceFragment", "服务器响应失败: " + response.code());
                }
            }
        });
    }

    private void addMonthSeparator(LayoutInflater inflater, String month) {
        View separatorView = inflater.inflate(R.layout.item_month_separator, containerBills, false);
        TextView tvMonth = separatorView.findViewById(R.id.tvMonthSeparator);

        // 格式化为 “2025年6月”
        String[] parts = month.split("-");
        String display = parts[0] + "年" + Integer.parseInt(parts[1]) + "月";
        tvMonth.setText(display);

        containerBills.addView(separatorView);
    }

    private void showEditDialog(BookKeep bill, LayoutInflater inflater) {
        View dialogView = inflater.inflate(R.layout.dialog_edit_bill, null);
        EditText editAmount = dialogView.findViewById(R.id.editAmount);
        EditText editCategory = dialogView.findViewById(R.id.editCategory);
        EditText editRemark = dialogView.findViewById(R.id.editRemark);
        EditText editTime = dialogView.findViewById(R.id.editTime);
        Spinner spinnerType = dialogView.findViewById(R.id.spinnerType);  // 替换editType

        Button btnConfirm = dialogView.findViewById(R.id.btnConfirm);
        Button btnCancel = dialogView.findViewById(R.id.btnCancel);

        // 初始化已有数据
        editAmount.setText(String.valueOf(bill.getPrice()));
        editCategory.setText(bill.getCategory());
        editRemark.setText(bill.getRemark());
        editTime.setText(bill.getAddTime());

        // 初始化Spinner数据
        String[] types = {"收入", "支出"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(),
                android.R.layout.simple_spinner_item, types);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerType.setAdapter(adapter);

        // 设置Spinner默认选中项
        spinnerType.setSelection(bill.getType() == 1 ? 0 : 1);

        // 时间选择器（数字选择模式）
        editTime.setOnClickListener(v -> {
            Calendar calendar = Calendar.getInstance();
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                Date date = sdf.parse(bill.getAddTime());
                if (date != null) calendar.setTime(date);
            } catch (Exception e) {
                e.printStackTrace();
            }

            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);

            new DatePickerDialog(requireContext(), (view1, y, m, d) -> {
                new TimePickerDialog(requireContext(), android.R.style.Theme_Holo_Light_Dialog_NoActionBar,
                        (view2, h, min) -> {
                            String datetime = String.format(Locale.getDefault(),
                                    "%04d-%02d-%02d %02d:%02d:00", y, m + 1, d, h, min);
                            editTime.setText(datetime);
                        }, hour, minute, true)
                        .show();
            }, year, month, day).show();
        });

        AlertDialog dialog = new AlertDialog.Builder(requireContext())
                .setView(dialogView)
                .setCancelable(false)
                .create();

        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        btnCancel.setOnClickListener(v -> dialog.dismiss());

        btnConfirm.setOnClickListener(v -> {
            String newAmount = editAmount.getText().toString();
            String newCategory = editCategory.getText().toString();
            String newRemark = editRemark.getText().toString();
            String newTime = editTime.getText().toString();

            int newType = spinnerType.getSelectedItemPosition() == 0 ? 1 : 0;

            if (newAmount.isEmpty() || newTime.isEmpty()) {
                Toast.makeText(getContext(), "金额和时间不能为空", Toast.LENGTH_SHORT).show();
                return;
            }


            updateBillOnServer(bill.getBookKeepId(), newAmount, newCategory, newRemark, newTime, newType);



            dialog.dismiss();
        });

        dialog.show();
    }


    private void updateBillOnServer(int bookKeepId, String amount, String category, String remark, String dateTime, int type) {
        OkHttpClient client = new OkHttpClient();

        // 使用fastjson构造json字符串
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("price", Double.parseDouble(amount));
        json.put("category", category);
        json.put("remark", remark);
        json.put("bookKeepDate", dateTime);
        json.put("type", type);

        RequestBody requestBody = RequestBody.create(json.toJSONString(), MediaType.get("application/json; charset=utf-8"));

        // 读取token，示例为从SharedPreferences读取
        SharedPreferences preferences = requireContext().getSharedPreferences("auth", Context.MODE_PRIVATE);
        String token = preferences.getString("token", "");
        System.out.println("token: " + token);
        Request request = new Request.Builder()
                .url(URLUtils.BASE_URL + "/bookKeep/" + bookKeepId)
                .put(requestBody)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                requireActivity().runOnUiThread(() ->
                        Toast.makeText(getContext(), "网络请求失败", Toast.LENGTH_SHORT).show()
                );
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String result = response.body().string();

                // 使用fastjson解析响应
                com.alibaba.fastjson.JSONObject res = com.alibaba.fastjson.JSONObject.parseObject(result);
                int code = res.getIntValue("code");
                String msg = res.getString("message");

                requireActivity().runOnUiThread(() -> {
                    if (code == 1) {
                        Toast.makeText(getContext(), "修改成功", Toast.LENGTH_SHORT).show();
                        // 这里刷新界面数据
                        containerBills.removeAllViews(); // 清空之前的账单视图
                        fetchBillData(LayoutInflater.from(getContext())); // 重新请求数据并显示
                    } else {
                        Toast.makeText(getContext(), "修改失败：" + msg, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

            // 清空旧账单视图
            containerBills.removeAllViews();

            // 重新请求并加载账单数据
            fetchBillData(LayoutInflater.from(getContext()));
    }




}
